package etc.com.market;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import etc.com.market.R;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.os.Bundle;
import android.os.Environment;
import android.util.FloatMath;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.ZoomControls;

public class AndroidBitmap extends Activity implements OnTouchListener{
	
	
	static final int NONE = 0;
    static final int DRAG = 1;
    static final int ZOOM = 2;
	private final String imageInSD = Environment.getExternalStorageDirectory().toString() +"/parking1.jpg";
	private final String imageInSD01 = Environment.getExternalStorageDirectory().toString() +"/shuttle.png";
	private final String imageInSD02 = Environment.getExternalStorageDirectory().toString() +"/transportation.png";
	ImageView myImageView;
	//Spinner spinnerScale;
	SeekBar seekbarRotate;
	SeekBar seekbarSkewX, seekbarSkewY;
	TextView textSkewX, textSkewY;
	
	PointF mid;
	int i=1;
	int j=3;
	float curre;
	int Dragx;
	int Dragy;
    float zoom = 1f;
    int times =0;
	boolean park;
	boolean shutt;
	boolean transp;
	boolean flag;
	boolean flagbtn;
	boolean flagscale;
	float oldDist;
	int mode = NONE;
	private float mX;
    private float mY;
    private static final String TAG = "Touch" ;
	private static final String[] strScale 
		= {"0.2Pix", "0.5Pix", "1.0Pix", "2.0Pix"}; 
	private static final Float[] floatScale 
		= {0.2F, 0.5F, 1F, 2F};

	Matrix matrix = new Matrix();
    Matrix savedMatrix = new Matrix();
	private final int defaultSpinnerScaleSelection = 2;
	
	private ArrayAdapter<String> adapterScale;
	
	private float curScale = 1F;
	private float curRotate = 0F;
	private float curSkewX = 0F;
	private float curSkewY = 0F;
	
	private String m_path;
	private String m_filename;
	private ImageButton btnzoomin;
	private ImageButton btnzoomout;
	Bitmap bitmap;
	int bmpWidth, bmpHeight;
	MarketSystem app;
	ZoomControls zoomcontrols;
    /** Called when the activity is first created. */
    
    @Override
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.zoom);
        m_path = Environment.getExternalStorageDirectory().toString();
        
        myImageView = (ImageView)findViewById(R.id.imageview);
        app =((MarketSystem)getApplicationContext());
		Bundle extras = getIntent().getExtras();//.getSerializableExtra("Pos");
		int position = (Integer) extras.getSerializable("Pos");			
      		
        //spinnerScale = (Spinner)findViewById(R.id.scale);
        
        /*adapterScale = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, strScale);
        adapterScale.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);*/
        /*spinnerScale.setAdapter(adapterScale);
        spinnerScale.setSelection(defaultSpinnerScaleSelection);*/
        curScale = floatScale[defaultSpinnerScaleSelection];
        
//      //Check Image Existed
        if(!CheckExistImage(position)){
        	try {
				copyImage(position);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
        
        if(position ==0)
        {
        	bitmap = BitmapFactory.decodeFile(imageInSD);
        	park = true;
        }
        else if(position ==1)
        {
          	bitmap = BitmapFactory.decodeFile(imageInSD01);
            shutt = true;
        }
        else{
        	bitmap = BitmapFactory.decodeFile(imageInSD02);
        	transp = true;
        }
        
        bmpWidth = bitmap.getWidth();
        bmpHeight = bitmap.getHeight();
        
        drawMatrix();
        
        //spinnerScale.setOnItemSelectedListener(spinnerScaleOnItemSelectedListener);
       
        myImageView.setOnTouchListener(this);
        
//        if(position == 0)
//		{
//			String title1 = getResources().getStringArray(R.array.main_menu_str)[3];
//	        app.clndrHmAct.setTitle(title1);
//		}
//		else if(position==2)
//		{
//			String title2 = getResources().getStringArray(R.array.main_menu_str)[5];
//			app.clndrHmAct.setTitle(title2);
//		}
//		else// if(ChurchApp.THEMER_ID[position]==1)
//		{
//			String title3 = getResources().getStringArray(R.array.main_menu_str)[4];
//			app.clndrHmAct.setTitle(title3);
//		}
        GetControl();
        SetEvent();
    }
    
    private void GetControl(){
    	zoomcontrols  = (ZoomControls)this.findViewById(R.id.zoomcontrols);
    }
    
    private void SetEvent(){
    	
    	zoomcontrols.setOnZoomInClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	
            	if(times<3){
            	if(i>=3)i=3;
				else 
				i=i+1;
				curScale =  floatScale[i];
				drawMatrix();
				times = times +1;
				flagbtn=true;
            	}
            }
		});
    	zoomcontrols.setOnZoomOutClickListener(new View.OnClickListener() {
	            public void onClick(View v) {
	            	times =(times ==3)?0:times;
	            	if(i<=1)i=1;
    				else
    				i=i-1;
    				curScale = floatScale[i];
    				drawMatrix();
    				if (flag ==true && flagbtn ==true){
    					if(i==1){
    						Matrix matrix = new Matrix();
    						matrix.postScale(0.6f, 0.7f);
        			        matrix.postRotate(curRotate);
        			        matrix.postSkew(curSkewX, curSkewY);
        			         
        			        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bmpWidth, bmpHeight, matrix, true);
        			        myImageView.setImageBitmap(resizedBitmap);
        			        myImageView.scrollTo(0, 0);
    						
    					}
    					else{
    					Matrix matrix = new Matrix();
    					matrix.postScale(curScale, curScale);
    			        matrix.postRotate(curRotate);
    			        matrix.postSkew(curSkewX, curSkewY);
    			         
    			        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bmpWidth, bmpHeight, matrix, true);
    			        myImageView.setImageBitmap(resizedBitmap);
    			        myImageView.scrollTo(0, 0);
    					}
    		          }
	            }
	    });
     }
    private boolean CheckExistImage(int position){
		try{
		Bitmap bmp = null;
		String path =  "";
		if(position ==0){
			path = imageInSD;
		}else if(position ==1){
			path = imageInSD01;
		}else{
			path = imageInSD02;
		}
		File file = new File(path); 
		FileOutputStream fos = new FileOutputStream(file);
		bmp.compress( CompressFormat.PNG, 100, fos ); 
		fos.close(); 
		}
		catch (Exception e) {
			return false;
		}
		return true;
	}
	
	 private void copyImage(int position) throws IOException{
     	 InputStream myInput = this.getResources().openRawResource(MarketSystem.THEMER_ID[position]);
     	// Path to the just created empty db
     	String path =  "";
		if(position ==0){
			path = m_path + "/parking1.jpg";
		}else if(position ==1){
			path = m_path + "/shuttle.png";
		}else{
			path =m_path + "/transportation.png";
		}
     	 
     	//Open the empty db as the output strea
     	 File file = new File(path);
     	 // outStream = new FileOutputStream(file);
     	OutputStream myOutput = new FileOutputStream(file);
     	
     	//transfer bytes from the inputfile to the outputfile
     	byte[] buffer = new byte[1024];
     	int length;
     	while ((length = myInput.read(buffer))>0){
     		myOutput.write(buffer, 0, length);
     		System.out.println("Read: " + buffer.toString());
     	}
  
     	//Close the streams
     	myOutput.flush();
     	myOutput.close();
     	myInput.close();
     }
    private void drawMatrix(){
    	
    	Matrix matrix = new Matrix();
    	if (i==1 && transp == true)
    	matrix.postScale(0.6f, 0.7f);
    	else if (i==1 && shutt == true)
        	matrix.postScale(0.6f, 0.7f);
    	else if (i==1 && park == true)
        	matrix.postScale(0.6f, 0.7f);
    	else
    	matrix.postScale(curScale, curScale);
        matrix.postRotate(curRotate);
        matrix.postSkew(curSkewX, curSkewY);
         
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bmpWidth, bmpHeight, matrix, true);
        myImageView.setImageBitmap(resizedBitmap);
        myImageView.scrollTo(0, 0);
    }
    

    private SeekBar.OnSeekBarChangeListener seekbarRotateSeekBarChangeListener
    	= new SeekBar.OnSeekBarChangeListener(){

			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				// TODO Auto-generated method stub
				curRotate = progress;
				drawMatrix();
			}

			public void onStartTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub
				
			}

			public void onStopTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub
				
			}};
    
    private Spinner.OnItemSelectedListener spinnerScaleOnItemSelectedListener
    	= new Spinner.OnItemSelectedListener(){

			
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				curScale = floatScale[arg2];
				drawMatrix();
			}

			
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				//spinnerScale.setSelection(defaultSpinnerScaleSelection);
				curScale = floatScale[defaultSpinnerScaleSelection];
			}};
			private void dumpEvent(MotionEvent event) {
		    	   String names[] = { "DOWN" , "UP" , "MOVE" , "CANCEL" , "OUTSIDE" ,
		    	      "POINTER_DOWN" , "POINTER_UP" , "7?" , "8?" , "9?" };
		    	   StringBuilder sb = new StringBuilder();
		    	   int action = event.getAction();
		    	   int actionCode = action & MotionEvent.ACTION_MASK;
		    	   sb.append("event ACTION_" ).append(names[actionCode]);
		    	   if (actionCode == MotionEvent.ACTION_POINTER_DOWN
		    	         || actionCode == MotionEvent.ACTION_POINTER_UP) {
		    	      sb.append("(pid " ).append(
		    	      action >> MotionEvent.ACTION_POINTER_ID_SHIFT);
		    	      sb.append(")" );
		    	   }
		    	   sb.append("[" );
		    	   for (int i = 0; i < event.getPointerCount(); i++) {
		    	      sb.append("#" ).append(i);
		    	      sb.append("(pid " ).append(event.getPointerId(i));
		    	      sb.append(")=" ).append((int) event.getX(i));
		    	      sb.append("," ).append((int) event.getY(i));
		    	      if (i + 1 < event.getPointerCount())
		    	         sb.append(";" );
		    	   }
		    	   sb.append("]" );
		    	   Log.d(TAG, sb.toString());
		    	}

			
	public boolean onTouch(View v, MotionEvent event) {
		dumpEvent(event);
	    int action = event.getAction();
	 	int actionCode = action & MotionEvent.ACTION_MASK;
	 	final float x = event.getX();
		final float y = event.getY();
		    
			switch (actionCode) {
			case 0:
				 
				mX = x;
	            mY = y;
			    Log.d(TAG, "mode=DRAG");
			    if(i==1){
			    	Dragx = 5;
			    	Dragy = 0;
			    }
			    else if(i==2)
			    {
			    	Dragx = 120;
			    	Dragy = 70;
			    }
			    else if (i==0){
			    	Dragx = 5;
			    	Dragy = 0;
			    }
			    else
			    {
			    	Dragx = 400;
			    	Dragy = 320;
			    }
			    mode = DRAG;
			    flag= true;
			    break;
			case 5:
				  oldDist = spacing(event);
		    	   Log.d(TAG, "oldDist=" + oldDist);
		    	   if (oldDist > 10f)
		    	   {
		    	      savedMatrix.set(matrix);
		    	      mid = midPoint(event);
		    	      mode = ZOOM;
		    	      
		    	      Log.d(TAG, "mode=ZOOM" );
		    	   }
		    	break;
			case 2:
//				if (mode == DRAG && curScale != floatScale[0] && curScale != floatScale[1] ) {
				if (mode == DRAG ) {
				 float scrollX = myImageView.getScrollX();
	    		 float scrollY = myImageView.getScrollY();
	    			 if(scrollX > -Dragx && ( - event.getX(0)+ mX ) < 0 && scrollY > -Dragy && (-event.getY(0) + mY ) < 0)//move right
		 				{
		 					if(( - event.getX(0)+ mX ) + scrollX > -Dragx)
		 						myImageView.scrollBy((int)( - event.getX(0)+ mX ), 0);
		 					else
		 						myImageView.scrollBy((int)(  -Dragx -scrollX ), 0);
		 					if((-event.getY(0) + mY ) + scrollY > -Dragy)
		 						myImageView.scrollBy(0, (int)(-event.getY(0) + mY ));
		 					else
		 						myImageView.scrollBy(0, (int)(-scrollY - Dragy ));
		 				}
		 				else if(scrollX < Dragx && ( - event.getX(0)+ mX ) > 0 && scrollY > -Dragy && (-event.getY(0) + mY ) < 0)//move left
		 				{
		 					if(( - event.getX(0)+ mX ) + scrollX < Dragx)
		 						myImageView.scrollBy((int)( - event.getX(0)+ mX ), 0);
		 					else
		 						myImageView.scrollBy((int)( -scrollX + Dragx ), 0);
		 					if((-event.getY(0) + mY ) + scrollY > -Dragy)
		 						myImageView.scrollBy(0, (int)(-event.getY(0) + mY ));
		 					else
		 						myImageView.scrollBy(0, (int)(-scrollY - Dragy ));
		 				}
		 				else if(scrollX > -Dragx && ( - event.getX(0)+ mX ) < 0 && scrollY < Dragy && (-event.getY(0) + mY ) > 0)//move right
		 				{
		 					if(( - event.getX(0)+ mX ) + scrollX > -Dragx)
		 						myImageView.scrollBy((int)( - event.getX(0)+ mX ), 0);
		 					else
		 						myImageView.scrollBy((int)(  -Dragx - scrollX ), 0);
		 					if((-event.getY(0) + mY ) + scrollY < Dragy)
		 						myImageView.scrollBy(0, (int)(-event.getY(0) + mY ));
		 					else
		 						myImageView.scrollBy(0, (int)(-scrollY + Dragy ));
		 				}
		 				else if(scrollX < Dragx && ( - event.getX(0)+ mX ) > 0 && scrollY < Dragy && (-event.getY(0) + mY ) > 0)//move left
		 				{
		 					if(( - event.getX(0)+ mX ) + scrollX < Dragx)
		 						myImageView.scrollBy((int)( - event.getX(0)+ mX ), 0);
		 					else
		 						myImageView.scrollBy((int)(  -scrollX+ Dragx ), 0);
		 					if((-event.getY(0) + mY ) + scrollY < Dragy)
		 						myImageView.scrollBy(0, (int)(-event.getY(0) + mY ));
		 					else
		 						myImageView.scrollBy(0, (int)(-scrollY + Dragy ));
		 				}				
				mX = x;
	            mY = y;
			
				}else if (mode == ZOOM) {
		    	      float newDist = spacing(event);
		    	      Log.d(TAG, "newDist=" + newDist);
		    	      if(event.getPointerCount() > 1)
		    	      if (newDist - oldDist > 0) 
		    	      {
		    	    	  if(times<3){
				    	    	if(i>=3)i=3;
				  				else i=i+1;
				  				curScale =  floatScale[i];
				  				drawMatrix();
//				  				myImageView.scrollTo(0, 0);
				  				if(i==2)
				    	    	{
				    	    		curScale =  floatScale[i];
					  				drawMatrix();
				    	    	}
				  				flagscale =true;
				  				times = times +1;
		    	    	  }
		    	  	  }else
		    	  		{
		    	  		times =(times ==3)?0:times;
		    	  		  if(i<=1)i=1;
		    			  else i=i-1;
		    				curScale = floatScale[i];
		    				drawMatrix();
		    				if(i==2)
			    	    	{
			    	    		curScale =  floatScale[i];
				  				drawMatrix();
			    	    	}
		    				if (flag ==true && flagscale ==true){
		    					if(i==1){
		    						Matrix matrix = new Matrix();
		    						matrix.postScale(0.6f, 0.7f);
		        			        matrix.postRotate(curRotate);
		        			        matrix.postSkew(curSkewX, curSkewY);
		        			         
		        			        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bmpWidth, bmpHeight, matrix, true);
		        			        myImageView.setImageBitmap(resizedBitmap);
		        			        myImageView.scrollTo(0, 0);
		    						
		    					}
		    					else{
		    					Matrix matrix = new Matrix();
		    					matrix.postScale(curScale, curScale);
		    			        matrix.postRotate(curRotate);
		    			        matrix.postSkew(curSkewX, curSkewY);
		    			         
		    			        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bmpWidth, bmpHeight, matrix, true);
		    			        myImageView.setImageBitmap(resizedBitmap);
		    			        myImageView.scrollTo(0, 0);
		    					}
		    		          }
		    	      }
		    	   }
			}
	  return true;
	}
	private PointF midPoint(MotionEvent event) {
    	PointF point = new PointF();
    	   float x = event.getX(0) + event.getX(1);
    	   float y = event.getY(0) + event.getY(1);
    	   point.set(x / 2, y / 2);
    	   return point;
    	}
    private float spacing(MotionEvent event) {
    	   float x = event.getX(0) - event.getX(1);
    	   float y = event.getY(0) - event.getY(1);
    	   return FloatMath.sqrt(x * x + y * y);
    	}

}